package edu.scau.finance.skuRecord.service;

import edu.scau.core.Enum.SkuRecordType;
import edu.scau.finance.skuRecord.mapper.SkuRecordReportMapper;
import edu.scau.sku.service.SkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
public class SkuRecordReportServiceImpl implements SkuRecordReportService{
    @Autowired
    private SkuRecordReportMapper skuRecordReportMapper;
    @Autowired
    private SkuService skuService;
    @Override
    public List<Map<String, Object>> getSkuRecordOfTypeDaily(Date startDate, Date endDate) {
        List<Map<String,Object>> res=skuRecordReportMapper.getSkuRecordOfTypeDaily(startDate, endDate);
        return res;
    }

    @Override
    public List<Map<String, Object>> getQuantityGroupedBySkuCodeAndType(Date startDate, Date endDate) {
            Map<String, Map<String, Integer>> skuMap = new HashMap<>();
            List<Map<String,Object>> res=skuRecordReportMapper.getQuantityGroupedBySkuCodeAndType(startDate, endDate);
            for (Map<String, Object> record : res) {
                String skuCode = (String) record.get("skuCode");
                Integer type = (Integer) record.get("type");
                Integer quantity = ((BigDecimal) record.get("totalQuantity")).intValue();

                Map<String, Integer> typeMap = skuMap.getOrDefault(skuCode, new HashMap<>());

                String skuName = skuService.findSkuByCode(skuCode).getSkuName();
                //入库
                if (SkuRecordType.IN.getSignal()==type) {
                    typeMap.put("inQuantity", typeMap.getOrDefault("inQuantity", 0) + quantity);
                } else if (SkuRecordType.OUT.getSignal()==type) {
                    typeMap.put("outQuantity", typeMap.getOrDefault("outQuantity", 0) + quantity);
                }
                skuMap.put(skuName, typeMap);
            }

            List<Map<String, Object>> result = new ArrayList<>();
            for (Map.Entry<String, Map<String, Integer>> entry : skuMap.entrySet()) {
                Map<String, Object> row = new HashMap<>();
                row.put("skuName", entry.getKey());
                row.put("inQuantity", entry.getValue().getOrDefault("inQuantity", 0));
                row.put("outQuantity", entry.getValue().getOrDefault("outQuantity", 0));
                result.add(row);
            }

            return result;
    }

}
